#coding=utf-8
'''
Created on Nov 26, 2010
@author: liyinhui
@moduleName: pub.views
@description: 约定：带单个下划线_的方法,是模块私有方法,不在外部直接调用
'''
#--------导入框架包
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.shortcuts import render_to_response
from django.forms import ValidationError
from django.template.context import RequestContext
from django.contrib.auth import login, logout, authenticate
from django.contrib.auth.models import User

#--------导入应用包
#from office.models import Office
from forms import LoginForm, RegForm
import config.constants as CONSTANTS, config.tools as tools
from config.constants import host_locate


##--私有常量定义
_HOST_SESSION_KEY = 'DEFAULT_HOST'

#def _setHostToSession(func):
#    def wrapper(request, *args, **kw):
#        output = func(request, *args, **kw)
#        if not isinstance(output, dict):
#            return output
#        host = request.session.get(_HOST_SESSION_KEY, None)
#        if  host is None:
#            request.session[_HOST_SESSION_KEY] = 'http://%s' % request.META['HTTP_HOST']
#        return request
#    return wrapper

def _set_host_to_session(request):
    host = request.session.get(_HOST_SESSION_KEY, None)
    if  host is None:
        request.session[_HOST_SESSION_KEY] = 'http://%s' % request.META['HTTP_HOST']
    return request


def _set_constants_to_dic(request, dic):
    '''
    将传入的dic字典中再添加全局的键值对: NEXT,BEIAN,SITE_NAME,并返回.
    '''
    next_key = 'NEXT'
    dic['SITE_NAME'] = CONSTANTS.PUB_SITE_NAME
    if not dic.has_key(next_key):
        if request.META.has_key('HTTP_REFERER') \
            and (request.META['HTTP_REFERER'] != request.session[_HOST_SESSION_KEY] + request.META['PATH_INFO']):
            dic[next_key] = request.META['HTTP_REFERER']
        else:
            dic[next_key] = '%s/' % request.session[_HOST_SESSION_KEY]
    if not dic.has_key('BEIAN'):
        dic['BEIAN'] = ''
    return dic

##---模板字典包装函数---------------
def _app_dictionary(request, dic):
    '''
    将传入的dic字典中再添加两个全局的键值对: APP_PUB和NEXT,并返回.
    传入request是为了获取META['HTTP_REFERER']
    '''
    request = _set_host_to_session(request)
    dic = _set_constants_to_dic(request,dic)
    next=None
    try:
        next = request.GET['next']
    except Exception,e:
        pass
    if next is not None:
        dic['NEXT'] = next
    return dic

##---页面跳转包装函数（通用型）--------------------------------------
def _app_page(template, request, dic):
    '''
    通用的页面跳转包装函数，接收三个参数：
    template：模板名称
    request：request对象
    dic：模板要使用中的模板变量字典数据
    '''
    return render_to_response(template, _app_dictionary(request, dic), context_instance=RequestContext(request))

##--跳转next页面函数----------------
def _redirect_nextpage(request):
    '''
    跳转函数,跳转到表单的隐藏域REFERER指定的页面。
    多用于登陆、注册、或回复等，常结合表单使用。
    '''
    return HttpResponseRedirect(request.GET['next'])

##---验证视图判断函数-------------------------------------
def check_view(request, url):
    '''
    验证视图判断函数, 检查验证码或用户名
    '''
    if url =='code':
        return _check_code(request)
    elif url=='user':
        return _check_user(request)
    else:
        raise Http404

##---验证码检查--------------------------------------------------
def _check_code(request):
    '''
    验证码检查函数,与session中的验证码比较, 正确返回true,不正确返回false
    比较前将输入的值转小写(session中是小写的),前台就实现了不区分大小写
    '''
    verifyCode = request.GET['verifyCode']
    vcodeInSession = request.session[CONSTANTS.VERIFY_CODE_IN_SESSION]
    if str(verifyCode).lower() == vcodeInSession:
        return HttpResponse('true', mimetype='text/plain')
    else:
        return HttpResponse('false', mimetype='text/plain')

##---用户检查函数,AJAX方式的--------------------------------------------------
def _check_user(request):
    uname = request.GET['username'].strip()
    try:
        user = User.objects.get(username=uname)
    except User.DoesNotExist:
        return HttpResponse('1', mimetype='text/plain') #1表示可以继续注册.
    return HttpResponse('0', mimetype='text/plain') #0表示已存在,不能继续注册

##---站内路由，根据IP判断用户所在地区，然后跳转查询
#def router(request):
#    '''
#    站内路由，根据IP判断用户所在地区，然后跳转查询,
#    一般用于首次访问时,自动路转到'域名/城市'的URL
#    '''
#    if request.session.has_key("city_en"):
#        return HttpResponseRedirect(request.session["city_en"])
#    else:
#        ip = request.META["REMOTE_ADDR"]
#        city_cn = tools.ip2locate(ip)
#        city_en = tools.locate2host(city_cn)
#        request.session["city_cn"] = city_cn
#        request.session["city_en"] = city_en
#        return HttpResponseRedirect(city_en)

def reset_locate(request):
    '''
    重置用户所在的城市,用户在前台选择新的城市后
    重新设置session内的数据,前台页面数据也会发生相应的变化
    '''
    city_en = str(request.META['PATH_INFO']).replace("/", "")
    if request.session.has_key("city_en") and request.session["city_en"]==city_en:
            return home(request)
    city_cn = host_locate[city_en]
    try:
        from pub.models import City
        city = City.objects.get(pinyin=city_en)
    except Exception,e:
        city = None
    request.session["city"] = city
    request.session["city_en"] = city_en
    request.session["city_cn"] = city_cn
    return home(request)

def home(request):
    '''
    首页渲染视图函数
    '''

    officeList = [] #Office.objects.all()[:6]
    #companyList = Company.objects.all()[:6]
    #jobList = Job.objects.all()[:20]
    #storeList = Store.objects.all()[:1]
    #commentList = Comment.objects.all()[:10]
    local = dict(officeList=officeList)
    return _app_page('index.html', request, local)

def logins(request):
    '''
    登录及处理页面函数
    '''
    if request.user.is_authenticated():
            return HttpResponseRedirect('/')
    local = {}
    form = LoginForm()
    if request.method == 'POST':
        uname = request.POST['username']
        pwd = request.POST['password']
        user = authenticate(username=uname, password=pwd)
        if user is not None:
            if user.is_active:
                login(request, user)
                return _redirect_nextpage(request)
            else:
                print '您的帐户已经被停用，请与客服联系!'
        else:
            print '您输入的用户名或密码不正确，请重新输入！'
    local['form'] = form
    return _app_page('login.html', request, local)

def verify_code(request):
    '''
    验证码生成视图,返回一个png格式的图像流,需要PIL库支持
    '''
    li = tools.build_verify_code()
    request.session[CONSTANTS.VERIFY_CODE_IN_SESSION] = str(li[0]).lower()
    return HttpResponse(li[1].getvalue(),'image/png')

def reg(request):
    '''
    注册及提交处理页面视图函数
    '''
    if request.user.is_authenticated():
        return HttpResponseRedirect('/')
    local = {}
    form = RegForm()
    if request.method == 'POST':
        form = RegForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                return _redirect_nextpage(request)
            except ValidationError,e:
                form.errors = e.value
    local['form'] = form
    return _app_page('reg.html', request, local)

def logouts(request):
    '''退出系统'''
    logout(request)
    return HttpResponseRedirect('/')